﻿
using System;
using System.IO;
using System.Reflection.Metadata;
using System.Text;

namespace HBase {
    public class FileLogger {
        private static readonly FileLogger f = new FileLogger();
        public static void Error(string message,Exception ex) {
            f.w(message,ex);

        }
        DateTime begin=new DateTime();
        StreamWriter _logWriter = null;



        private String installSW() {
         
            string currentDirectory = Directory.GetCurrentDirectory();
            String dir = currentDirectory + Path.DirectorySeparatorChar + "log";

            if (!File.Exists(dir)) {
                Directory.CreateDirectory(dir);
            }

            dir = dir + Path.DirectorySeparatorChar + begin.Year;
            if (!File.Exists(dir)) {
                Directory.CreateDirectory(dir);
            }
            dir = dir + Path.DirectorySeparatorChar + begin.Month;

            if (!File.Exists(dir)) {
                Directory.CreateDirectory(dir);
            }
            String name = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".log";
            String fileName = dir + Path.DirectorySeparatorChar + name;
            if (!File.Exists(fileName)) {
               var f= File.Create(fileName);
                f.Close();
             }
            return fileName;
          
        }
        private void w(string message,Exception ex) {
            var n = DateTime.Now;
            lock (f) {
                if (n.Year != begin.Year || n.Month != begin.Month || n.Day != begin.Day) {
                       begin = n;
                        String fileName= installSW();
                      _logWriter = new StreamWriter(fileName,true,Encoding.UTF8);
                }

                String t = n.ToString("HH:mm:ss.FFF->");

                _logWriter.WriteLine(t + message);
                if (ex != null) {
                    _logWriter.WriteLine(t + ex.Message);
                    try{ 
                         String v=ex.StackTrace;
                         _logWriter.WriteLine(v);  
                    }catch{ 
                        Console.WriteLine("保存错误日志时获取堆栈异常");
                    }
                 
                }

                _logWriter.Flush();

            }

        }


        ~FileLogger() {
            _logWriter.Close();
        }

    }
}
